package com.house365.core.sop;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.house365.core.R;
import com.house365.core.constant.CorePreferences;
import com.house365.core.sop.bean.Share;
import com.house365.core.sop.bean.ShareType;
import com.house365.core.sop.message.SystemMessage;
import com.house365.core.sop.weixin.WXEntryApp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXWebpageObject;

/**
 * 分享通用组件
 * 
 * @author Vincent Chow
 * @version V4.1 创建时间：2013-12-2 下午 3:35:45
 * @author liuziqiang
 * @version V5.0.2 修改时间：2014-2-12 下午 3:15:18
 */
public class ShareUtil implements View.OnClickListener,
		OnActivityResultListener {
	private static final String TAG = "ShareUtil";
	private static PopupWindow shareWindow;
	private static ShareUtil shareUtil;
	/**
	 * 新浪微博
	 */
	private TextView sinaWeibo;
	/**
	 * 微信
	 */
	private TextView weixin;
	/**
	 * 朋友圈
	 */
	private TextView friendCircle;
	/**
	 * QQ空间
	 */
	private TextView qqzone;
	/**
	 * 腾讯微博
	 */
	private TextView tencentWeibo;
	/**
	 * 手机信息
	 */
	private TextView system_sms;

	private Button cancelButton;
	/**
	 * popLayoutView
	 */
	private View contentView;
	private Share share;
	/**
	 * 同步对象
	 */
	public static Object syncObj = new Object();

	private Context context;


	/**
	 * 提示语
	 */
	private String toastText;

	public static ShareUtil getInstance() {
		if (shareUtil == null) {
			shareUtil = new ShareUtil();
		}
		return shareUtil;
	}

	/**
	 * 打开分享界面
	 */
	public void show(Context context, final View anchor) {
		this.context = context;
		// share.setActivityResultListener(this);
		if (shareWindow == null) {
			
			contentView = LayoutInflater.from(context.getApplicationContext())
					.inflate(R.layout.sop_share_poplayout, null);
			shareWindow = new PopupWindow(contentView,WindowManager.LayoutParams.FILL_PARENT,WindowManager.LayoutParams.FILL_PARENT);
//			shareWindow.setContentView(contentView);
			shareWindow.setFocusable(true);
			shareWindow.setTouchable(true);
			shareWindow.setBackgroundDrawable(context.getApplicationContext()
					.getResources().getDrawable(android.R.color.transparent));
			shareWindow.setOutsideTouchable(false);
			// 新浪微博
			sinaWeibo = (TextView) contentView.findViewById(R.id.sina_weibo);
			sinaWeibo.setOnClickListener(this);
			// 微信好友
			weixin = (TextView) contentView.findViewById(R.id.weixin);
			weixin.setOnClickListener(this);
			// 微信朋友圈
			friendCircle = (TextView) contentView
					.findViewById(R.id.friend_circle);
			friendCircle.setOnClickListener(this);
			// 信息
			system_sms = (TextView) contentView.findViewById(R.id.system_msg);
			system_sms.setOnClickListener(this);
			// QQ空间
			qqzone = (TextView) contentView.findViewById(R.id.qqzone);
			qqzone.setOnClickListener(this);
			// 腾讯微博
			tencentWeibo = (TextView) contentView.findViewById(R.id.tencent_weibo);
			tencentWeibo.setOnClickListener(this);
			WindowManager wm = (WindowManager) context.getApplicationContext()
					.getSystemService(Context.WINDOW_SERVICE);
			int screenWidth = (int) (wm.getDefaultDisplay().getWidth() - context
					.getResources().getDimension(R.dimen.screen_width));
			cancelButton = (Button) contentView
					.findViewById(R.id.share_poplayout_cancel);
			cancelButton.getLayoutParams().height = (int) (screenWidth / 388.0 * 49);
			cancelButton.setOnClickListener(this);
			View shadow=contentView.findViewById(R.id.share_shadow);
			shadow.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					shareWindow.dismiss();
				}
			});
		}
		if (!shareWindow.isShowing()) {
			shareWindow.showAtLocation(anchor, Gravity.BOTTOM, 0, 0);
		}
	}

	/**
	 * 图片处理
	 * 
	 * @return
	 */
	public byte[] getThumbData(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		byte[] bytes = Util.bmpToByteArray(bitmap, false);
		Bitmap adjustThumb = null;
		while (bytes.length > 32000) {
			width = width / 4;
			height = height / 4;
			adjustThumb = Bitmap
					.createScaledBitmap(bitmap, width, height, true);
			bytes = Util.bmpToByteArray(adjustThumb, false);
		}
		if (adjustThumb != null && !adjustThumb.isRecycled()) {
			share.setThumb(adjustThumb);
			bitmap.recycle();
		} else {
			share.setThumb(bitmap);
			adjustThumb.recycle();
		}
		return bytes;
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		if (view.getId() == R.id.weixin) {
			new Thread() {
				public void run() {
					share.setFriendCircle(false);
					initWeiXin();
					weixinApi();
				};
			}.start();
		} else if (view.getId() == R.id.sina_weibo) {
//			new Thread() {
//				public void run() {
//					sinaWeiboAPi();
//				};
//			}.start();
			shareToApp(context, "com.sina.weibo", "", share.getSystemMsg(), "", "");
		} else if (view.getId() == R.id.system_msg) {

			SystemMessage.sendMsg(context, share.getSystemMsg());

		} else if (view.getId() == R.id.friend_circle) {
			share.setFriendCircle(true);
			new Thread() {
				public void run() {
					initWeiXin();
					weixinApi();
				};
			}.start();
		}else if (view.getId() == R.id.qqzone) {
			shareToApp(context, "com.qzone", "", share.getSystemMsg(), "", "");
		}else if (view.getId() == R.id.tencent_weibo) {
			shareToApp(context, "com.tencent.WBlog", "", share.getSystemMsg(), "", "");
		}
		shareWindow.dismiss();
	}

	private void initWeiXin() {
		// 微信
		WXWebpageObject obj = new WXWebpageObject();
		obj.webpageUrl = share.getWebpageUrl();
		share.setMediaObject(obj);
		share.setShareType(ShareType.WEBPAGE);
		Bitmap bmp = null;
		try {
			if(!StringUtils.isEmpty(share.getThumbUrl())){
				byte[] b = Util.compressInputStreamToByte(new URL(share.getThumbUrl()).openStream(), 20);
				share.setThumbData(b);
			}else {
				bmp=BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_share);
				share.setThumb(bmp);
			}
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/*
	 * 微信和朋友圈
	 */
	public void weixinApi() {
		IWXAPI api = WXAPIFactory.createWXAPI(context, Constants.WEIXIN_APP_ID);
		if (!api.isWXAppInstalled()) {
			toastText = context.getString(R.string.not_install_weixin);
			handler.sendMessage(handler.obtainMessage());
			return;
		}
		new WXEntryApp(context, share, api);
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			Toast.makeText(context, toastText, Toast.LENGTH_SHORT).show();
		}
	};

	/**
	 * 腾讯微博分享
	 */
	private synchronized void tencentWeiboApi() {
		// if(validateTencentWeibo()){
		// UserAPI userAPI;
		// TAPI tAPI;
		// tAPI = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
		// try {
		// String response = tAPI.add(oAuth, "json", "Android客户端文字微博2",
		// "127.0.0.1");
		// Log.e(TAG, "======tencentWeiboApi========="+response);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// tAPI.shutdownConnection();
		// }
	}

	private boolean validateTencentWeibo() {
		// oAuth = new OAuthV2(redirectUri);
		// oAuth.setClientId(clientId);
		// oAuth.setClientSecret(clientSecret);
		//
		// sharedPrefsUtil = new SharedPreferencesUtil(context);
		// OAuthV2 v2 = null;
		// try {
		// v2 = (OAuthV2) sharedPrefsUtil.getObject(SAVED_KEY, OAuthV2.class);
		// Log.e(TAG, "=====init===="+v2);
		// } catch (SharedPreferenceException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// // 关闭OAuthV2Client中的默认开启的QHttpClient。
		// OAuthV2Client.getQHttpClient().shutdownConnection();
		//
		// if (v2==null||v2.getStatus() != 0) {
		// Intent intent = new Intent(context,
		// OAuthV2AuthorizeWebView.class);// 创建Intent，使用WebView让用户授权
		// intent.putExtra("oauth", oAuth);
		// ((Activity)context).startActivityForResult(intent, Share.RESULT_ID);
		// return false;
		// }
		return true;
	}

	/*
	 * 通过读取OAuthV2AuthorizeWebView返回的Intent，获取用户授权信息
	 */
	public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
		// if (requestCode == Share.RESULT_ID) {
		// if (resultCode == OAuthV2AuthorizeWebView.RESULT_CODE) {
		// oAuth = (OAuthV2) data.getExtras().getSerializable("oauth");
		// if (oAuth.getStatus() == 0){
		// sharedPrefsUtil.putObject(SAVED_KEY, oAuth);
		// Toast.makeText(context.getApplicationContext(),
		// "登陆成功",Toast.LENGTH_SHORT).show();
		// }
		//
		// }
		// }
		return false;
	}

	public void setShare(Share share) {
		this.share = share;
	}
	
	public static List<ResolveInfo> getShareList(Context paramContext) {
		Intent localIntent = new Intent("android.intent.action.SEND", null);
		localIntent.addCategory("android.intent.category.DEFAULT");
		localIntent.setType("image/*");
		return paramContext.getPackageManager().queryIntentActivities(localIntent, 0);
	}
	
	public boolean shareToApp(Context paramContext, String targetPackage, String paramString2, String shareText, String paramString4, String paramString5)
    {
    	//本地所有可发送程序
      List<ResolveInfo> localList = getShareList(paramContext);
      if ((localList == null) || (localList.size() == 0)){
    	  return false;
      }
      
      ResolveInfo targetR = null;
      boolean hasApp = false;
      for (ResolveInfo rinfo : localList) {
		if(targetPackage.equals(rinfo.activityInfo.packageName)){
			hasApp = true;
			targetR = rinfo;
			break;
		}
      }
      if(!hasApp){
    	  Toast.makeText(paramContext, "您还没有安装该应用哦，请先下载安装后再分享", Toast.LENGTH_SHORT).show();
    	  return false;
      }
      
      Intent localIntent1 = new Intent("android.intent.action.SEND");
      if (TextUtils.isEmpty(paramString4))
      {
//        File localFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/newhouse/res/../ic_launcer");
//        boolean bool2 = localFile.exists();
//        Uri localUri = null;
//        if (bool2)
//        {
//          localUri = Uri.fromFile(localFile);
//        }
    	  
        Uri localUri = null;
		try {
			localUri = Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), share.getThumb(), null,null));;
		} catch (Exception e) {
			CorePreferences.ERROR(e);
		}
        if (localUri != null){
        	localIntent1.putExtra("android.intent.extra.STREAM", localUri);
        }
      }
      
      
      localIntent1.setType("image/*");
      localIntent1.putExtra("android.intent.extra.TEXT", shareText);
      localIntent1.putExtra("sms_body", shareText);
      localIntent1.setClassName(targetR.activityInfo.packageName, targetR.activityInfo.name);
      localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      paramContext.startActivity(localIntent1);
      return true;
    }

	public void setActivity(Context activity) {
		context = activity;
	}
}
